<?php

namespace api\controllers;

use api\components\PaysRed;
use api\components\PaysToUser;
use api\components\PayToUser;
use api\service\ShopService;
use backend\models\MallBill;
use teach\service\Shops;
use teach\util\helper\ResponseHelper;
use Yii;
use yii\filters\Cors;
use yii\rest\ActiveController;
use yii\web\Response;
use PHPExcel;

class ShopController extends ActiveController
{
    public $modelClass = '';

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        $behaviors['corsFilter'] = [
            'class' => Cors::class,
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Request-Method' => ['POST', 'HEAD'],
                'Access-Control-Request-Headers' => ['*'],
                'Access-Control-Allow-Credentials' => true,
                'Access-Control-Max-Age' => 86400,
            ],
        ];
        return $behaviors;
    }

    /**
     * 商家信息
     */
    public function actionInfo()
    {
        $request = Yii::$app->request;
        $uid = $request->post('uid');

        $msg = '';
        $flag = false;
        if (!$uid) {
            $msg = 'uid 不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            //通过uid获取公众号用户表跟小程序连表，如果查询无此人返回exception
            /**
             * $shopService = new ShopService();
             * $shop = $shopService->userPubMin($uid);
             * if ($shop) {
             * // 统计未处理订单
             * $shop['wait_deal'] = $shopService->unDeal($shop['mini_id']);
             * $jsonData = ResponseHelper::buildJsonData(400, '成功', $shop);
             * } else {
             * $qqURL = "https://mp.weixin.qq.com";
             * header("Location:{$qqURL}");// 返回到一个错误页面, 让用户扫码或者其他方式跳转到小程序再进来
             * $jsonData = ResponseHelper::buildJsonData(302, '跳转');
             * }
             * */

            $shopService = new ShopService();

            //查出用户是否roles = 1;如果是的话把uid改成
            $user = $shopService->isRoles($uid);
            if ($user) {
                $uid = $user['mall_id'];
            }
            $shop = $shopService->userMin($uid);
            if ($shop) {
                // 统计未处理订单
                $shop['wait_deal'] = $shopService->unDeal($shop['mini_id']);
                $jsonData = ResponseHelper::buildJsonData(200, '成功', $shop);
            } else {
                $jsonData = ResponseHelper::buildJsonData(400, '用户不存在,非法操作');
            }
        }
        return $this->asJson($jsonData);
    }

    /**
     * 用户提现列表
     * @return Response
     */
    public function actionAppearList()
    {
        $request = Yii::$app->request;
        $mid = $request->post('mid');
        $status = $request->post('status'); //0全部1提现中 2成功3失败
        $uid = $request->post('uid');//用户id

        $msg = '';
        $flag = false;
        if (!$mid) {
            $msg = 'mid 不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            $page = $request->post('page');
            $page = $page ? $page : 1;
            $map = " mid = {$mid} ";
            if ($status) {
                $map .= " AND status = {$status} ";
            }
            if ($uid) {
                $map .= " AND uid = {$uid} ";
            }
            $shopService = new ShopService();
            $appearList = $shopService->appearAmount($map, $page, $pre_page = 10);
            $jsonData = ResponseHelper::buildJsonData(200, '成功', $appearList);
        }
        return $this->asJson($jsonData);
    }

    /**
     * 查找其中一条申请记录
     * @return Response
     */
    public function actionAppearNo()
    {
        $request = Yii::$app->request;
        $order_num = $request->post('order_num');//申请的订单号

        $msg = '';
        $flag = false;
        if (!$order_num) {
            $msg = 'order_num 不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            $shopService = new ShopService();
            $appearDetail = $shopService->appearDetail($order_num);
            if ($appearDetail) {
                $jsonData = ResponseHelper::buildJsonData(200, '成功', $appearDetail);
            } else {
                $jsonData = ResponseHelper::buildJsonData(400, '失败');
            }
        }

        return $this->asJson($jsonData);
    }

    /**
     * 发起企业付款到零钱
     * @return Response
     */
    public function actionEnsure()
    {
        $request = Yii::$app->request;

        $mid = $request->post('mid');
        $order_num = $request->post('order_num');
        $is_refuse = $request->post('is_refuse'); //1通过 2拒绝
        $tid = $request->post('tid');//1红包, 2 企业零钱支付
        $uid = $request->post('uid');//点击确认提现的用户的id

        $msg = '';
        $flag = false;
        if (!$order_num) {
            $msg = 'order_num 单号不能为空';
        } elseif (!$is_refuse) {
            $msg = 'is_refuse 不能为空';
        } elseif (!$mid) {
            $msg = 'mid 商家id不能为空';
        } elseif (!$uid) {
            $msg = 'uid 不能为空';
        } elseif (!$tid) {
            $msg = 'tid 提现模式不能为空';
        } elseif ($tid != 2) {
            $msg = '提现模式错误';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            if (!in_array($is_refuse, [1, 2])) {
                $jsonData = ResponseHelper::buildJsonData(400, 'is_refuse 有误');
                return $this->asJson($jsonData);
            }
            $shopService = new ShopService();
            //判断用户是否在此商家下的用户并判断有没有执行的权限
            $user = $shopService->userAuth($uid, $mid);
            if (!$user) {
                $jsonData = ResponseHelper::buildJsonData(400, '用户没有操作权限');
                return $this->asJson($jsonData);
            }

            //判断商户是否存在
            if (!array_key_exists($mid, Yii::$app->params['serviceNum'])) {
                $jsonData = ResponseHelper::buildJsonData(400, '商家支付账号不存在,请联系商家或者开发者');
                return $this->asJson($jsonData);
            }

            //判断是否开通了企业付款到零钱
            if (!array_key_exists('md5Key', Yii::$app->params['serviceNum'][$mid])) {
                $jsonData = ResponseHelper::buildJsonData(400, '商家还没有开通,请联系开发者');
                return $this->asJson($jsonData);
            }

            $map = " order_num = '{$order_num}' AND status = 1 ";
            $appearDetail = $shopService->appearDetailOne($map);
            if (!$appearDetail) {
                $jsonData = ResponseHelper::buildJsonData(400, '订单不存在或已处理');
                return $this->asJson($jsonData);
            }

            //此用户发起提现确认
            if ($is_refuse == 1) {
                $appid = Yii::$app->params['serviceNum'][$mid]['sub_appid'];
                $openid = $appearDetail['openid'];
                $mch_id = Yii::$app->params['serviceNum'][$mid]['sub_mch_id'];
                $key = Yii::$app->params['serviceNum'][$mid]['md5Key'];
                $out_trade_no = 'Ca' . date('Ymd') .time() .str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
                $body = '奖励提现';
                $total_fee = $appearDetail['amount'];
                $spbill_create_ip = $_SERVER['REMOTE_ADDR'];
                $paysToUser = new PaysToUser($appid, $openid, $mch_id, $key, $out_trade_no, $body, $total_fee, $spbill_create_ip, $mid);
                $result = $paysToUser->send();

                if ($result['return_code'] == 'SUCCESS') {
                    if ($result['return_msg'] == "支付失败") {
                        $jsonData = ResponseHelper::buildJsonData(400, '失败:' . $result['err_code_des'] . '.请联系开发者');
                        return $this->asJson($jsonData);
                    } else {
                        //将冻结金额去掉 放入到已提现的金额里
                        $shopService->userDelAmount($appearDetail['openid'], $appearDetail['amount']);
                        //将这条记录改为已提现
                        $shopService->appearChange($appearDetail['id'], $tid, $uid, json_encode($result));
                        $jsonData = ResponseHelper::buildJsonData(200, '成功');
                        return $this->asJson($jsonData);
                    }
                } else {
                    $jsonData = ResponseHelper::buildJsonData(400, $result);
                    return $this->asJson($jsonData);
                }

            }

            //拒绝
            if ($is_refuse == 2) {
                $reason = $request->post('reason');
                if (!$reason) {
                    $jsonData = ResponseHelper::buildJsonData(400, '请填写拒绝的理由');
                    return $this->asJson($jsonData);
                }
                //更新记录
                $shopService->appearChangeDel($appearDetail['id'], $uid, $reason);
                //把提现金额返回
                $shopService->userAddAmount($appearDetail['openid'], $appearDetail['amount']);

                $jsonData = ResponseHelper::buildJsonData(200, '拒绝成功');
                return $this->asJson($jsonData);
            }

            $jsonData = ResponseHelper::buildJsonData(400, '操作越区');

        }
        return $this->asJson($jsonData);


    }

    /**
     * 确认或者拒绝用户提现
     * @return Response
     */
    public function actionEnsures()
    {
        $request = Yii::$app->request;
        $mid = $request->post('mid');
        $order_num = $request->post('order_num');
        $is_refuse = $request->post('is_refuse');//1通过 2拒绝
        $tid = $request->post('tid'); //1红包 2 企业零钱支付


        $msg = '';
        $flag = false;
        if (!$order_num) {
            $msg = 'order_num 不能为空';
        } elseif (!$is_refuse) {
            $msg = 'is_refuse 不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            $shopService = new ShopService();
            $map = " order_num = '{$order_num}' AND status = 1 ";
            $appearDetail = $shopService->appearDetailOne($map);
            if (!$appearDetail) {
                $jsonData = ResponseHelper::buildJsonData(400, '订单不存在或已处理');
                return $this->asJson($jsonData);
            }

            //通过
            if ($is_refuse == 1) {
                //tid = 1 用户金额只能 1-200 tid = 2 可以无限制
                if (!$tid) {
                    $jsonData = ResponseHelper::buildJsonData(400, '请选择提现方式');
                    return $this->asJson($jsonData);
                }

                //查找商家的充值的金额
                $shop = $shopService->shopOne($mid);

                //用红包方式给用户提现
                if ($tid == 1) {
                    if ($shop['is_red'] != 1) {
                        $jsonData = ResponseHelper::buildJsonData(400, '暂时未开通红包提现');
                        return $this->asJson($jsonData);
                    }
                    if ($appearDetail['amount'] < 1 || $appearDetail['amount'] > 200) {
                        $jsonData = ResponseHelper::buildJsonData(400, '发红包必须在￥1-200之间');
                        return $this->asJson($jsonData);
                    }

                    //判断商户是否存在
                    if (!array_key_exists($mid, Yii::$app->params['serviceNum'])) {
                        $jsonData = ResponseHelper::buildJsonData(400, '商家支付账号不存在,请联系商家或者开发者');
                        return $this->asJson($jsonData);
                    }

                    //TODO 发起红包提现
                    $sender = Yii::$app->params['serviceNum'][$mid]['name'];
                    $data['wxappid'] = Yii::$app->params['serviceNum'][$mid]['appid'];//公众号appid
                    $data['msgappid'] = Yii::$app->params['serviceNum'][$mid]['sub_appid'];//子商户appid or 小程序
                    $data['mch_id'] = Yii::$app->params['serviceNum']['mchId'];//商户号
                    $data['sub_mch_id'] = Yii::$app->params['serviceNum'][$mid]['sub_mch_id'];//子商户号
                    $data['mch_billno'] = 'Red' . date('Ymd') . time() . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
                    //$data['mch_billno'] = 'Red' . 111111111111111111;
                    $data['re_openid'] = $appearDetail['openid'];//接收红包的openid
                    $data['total_amount'] = $appearDetail['amount'] * 100;//  单位分， 元转成分
                    $data['total_num'] = 1;//红包数
                    $data['send_name'] = $sender;
                    $data['wishing'] = '感谢您推送本商城,祝你万事顺意';
                    $data['client_ip'] = $_SERVER['REMOTE_ADDR'];
                    $data['act_name'] = '用户奖励回馈';
                    $data['remark'] = '推送越多奖励越多';

                    $PaysRed = new PaysRed();
                    $res = $PaysRed->payLuckyMoney('common', $data);

                    //判断返回值中是否发送成功
                    if ($res) {
                        if ($res['return_code'] == 'SUCCESS') {
                            if ($res['result_code'] == 'SUCCESS') {
                                //发放成功，请用户注意接收微信消息
                                $shopService->appearSuccess($appearDetail['id'], $tid, $mid, json_encode($res), $res['mch_billno']);
                                $jsonData = ResponseHelper::buildJsonData(200, '佣金发送成功,请提醒用户及时领取');
                                return $this->asJson($jsonData);
                            } else {
                                $jsonData = ResponseHelper::buildJsonData(400, $res);
                                return $this->asJson($jsonData);
                            }
                        } else {
                            $jsonData = ResponseHelper::buildJsonData(400, $res);
                            return $this->asJson($jsonData);
                        }
                    } else {
                        $jsonData = ResponseHelper::buildJsonData(400, '发送错误,请联系开发者');
                        return $this->asJson($jsonData);
                    }
                }

                if ($tid == 2) {
                    //在小程序给用户发起提现
                    if ($shop['recharge'] < $appearDetail['amount']) {
                        $jsonData = ResponseHelper::buildJsonData(400, '您的余额不足,请先充值后在发起提现');
                        return $this->asJson($jsonData);
                    }

                    $pay = new PayToUser();
                    $result = $pay->send($appearDetail['openid'], $appearDetail['amount']);
                    if ($result['return_code'] == 'SUCCESS') {
                        if ($result['return_msg'] == "支付失败") {
                            // 支付失败下不给处理 重新发起支付
                            $jsonData = ResponseHelper::buildJsonData(400, '失败:' . $result['err_code_des'] . '.请联系开发者');
                            return $this->asJson($jsonData);
                        }

                        //商家减去用去的金额
                        $shopService->shopDeaAmount($mid, $appearDetail['amount']);
                        //将冻结金额去掉 放入到已提现的金额里
                        $shopService->userDelAmount($appearDetail['openid'], $appearDetail['amount']);
                        //将这条记录改为已提现
                        $shopService->appearChange($appearDetail['id'], $tid, $mid, json_encode($result));
                        //TODO 给用户发送公众号消息
                        $jsonData = ResponseHelper::buildJsonData(200, '成功');
                        return $this->asJson($jsonData);
                    }

                }
            }
            //拒绝
            if ($is_refuse == 2) {
                $reason = $request->post('reason');
                if (!$reason) {
                    $jsonData = ResponseHelper::buildJsonData(400, '请填写拒绝的理由');
                    return $this->asJson($jsonData);
                }
                //更新记录
                $shopService->appearChangeDel($appearDetail['id'], $mid, $reason);
                //把提现金额返回
                $shopService->userAddAmount($appearDetail['openid'], $appearDetail['amount']);

                $jsonData = ResponseHelper::buildJsonData(200, '拒绝成功');
                return $this->asJson($jsonData);

            }

            $jsonData = ResponseHelper::buildJsonData(400, '操作越区');

        }

        return $this->asJson($jsonData);

    }

    /**
     * 每个客户的收益明细
     * @return Response
     */
    public function actionProfitList()
    {
        $request = Yii::$app->request;
        $mid = $request->post('mid');//商家id
        $uid = $request->post('uid');//客户id 搜索时用的

        $msg = '';
        $flag = false;
        if (!$mid) {
            $msg = 'mid 不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            $page = $request->post('page');
            $page = $page ? $page : 1;
            $map = " mall_id = {$mid} AND mall_is = 0 ";
            //$nickname = $request->post('nickname');
            if ($uid) {
                if (is_numeric($uid)) {
                    $map .= " AND id = {$uid} ";
                } else {
                    $map .= " AND nickname LIKE '%{$uid}%' ";
                }
            }
            /**
             * if ($uid) {
             * $map .= " AND id = {$uid} ";
             * }
             * if ($nickname) {
             * $map .= " AND nickname LIKE '%{$nickname}%' ";
             * }
             * */
            $shopService = new ShopService();
            $customsList = $shopService->shopCustoms($map, $page, $pre_page = 10);
            $jsonData = ResponseHelper::buildJsonData(200, '成功', $customsList);
        }
        return $this->asJson($jsonData);
    }

    /**
     * 导出excel到邮箱
     * @return Response
     */
    public function actionExcel()
    {
        $request = Yii::$app->request;
        $uid = $request->post('uid');
        $where = $request->post('where');//1.全部 2.今日收益 3.已到账收益 4.待到账收益
        $out_trade_no = $request->post('out_trade_no');//订单号
        $timeStart = $request->post('time_start'); //开始时间
        $timeEnd = $request->post('time_end'); //结束时间
        $email = $request->post('email');

        $msg = '';
        $flag = false;
        if (!$uid) {
            $msg = 'uid不能为空';
        } elseif (!$where) {
            $msg = '条件不能为空';
        } elseif (!$email) {
            $msg = 'email不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            //TODO 判断商家是否有填写邮箱
            $andWhere = " uid = {$uid} ";
            if ($timeStart) {
                $andWhere .= " AND create_time > {$andWhere} ";
            }
            if ($timeEnd) {
                $timeEnd = 24 * 36000;
                $andWhere .= " AND create_time < {$timeEnd} ";
            }
            if ($out_trade_no) {
                $andWhere .= " AND out_trade_no = {$out_trade_no} ";
            }
            if ($where == 3) {
                $andWhere .= " AND status = 1 ";
            }
            if ($where == 4) {
                $andWhere .= " status = 2 ";
            }

            $shops = new ShopService();
            $res = $shops->userProfitDetail($andWhere);

            $objPHPExcel = new PHPExcel();
            //$objPHPExcel->getActiveSheet()->getColumnDimension(\PHPExcel_cell::stringFromColumnIndex(0))->setAutoSize(true);
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', '用户id')
                ->setCellValue('B1', '订单号')
                ->setCellValue('C1', '金额')
                ->setCellValue('D1', '来源')
                ->setCellValue('E1', '入账时间')
                ->setCellValue('F1', '结算时间')
                ->setCellValue('G1', '订单用户')
                ->setCellValue('H1', '订单电话')
                ->setCellValue('I1', '折扣金额')
                ->setCellValue('J1', '订单折扣值')
                ->setCellValue('K1', '总费用');;

            foreach ($res as $key => $value) {
                $num = $key + 2;
                $order = $shops->orderMessage($value['out_trade_no']);
                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A' . $num, $value['uid'])
                    ->setCellValue('B' . $num, $value['out_trade_no'])
                    ->setCellValue('C' . $num, $value['amount'])
                    ->setCellValue('D' . $num, $value['direct_text'])
                    ->setCellValue('E' . $num, date("Y-m-d H:i:s", $value['create_time']))
                    ->setCellValue('F' . $num, $value['finish_time'] ? date("Y-m-d H:i:s", $value['finish_time']) : '')
                    ->setCellValue('G' . $num, $order['name'])
                    ->setCellValue('H' . $num, $order['phone'])
                    ->setCellValue('I' . $num, $order['total_fee'])
                    ->setCellValue('J' . $num, $order['discount'])
                    ->setCellValue('K' . $num, $order['amount']);
            }

            $objPHPExcel->getActiveSheet()->setTitle('用户收益表');
            $objPHPExcel->setActiveSheetIndex(0);
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Cache-Control: max-age=0');
            header('Cache-Control: max-age=1');
            header('Pragma: public'); // HTTP/1.0
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
            $name = 'excel/' . date('Ymd') . time() . str_pad(mt_rand(1, 99999), 8, '0', STR_PAD_LEFT) . '_excel.xlsx';
            //$name = 'excel/abc.xlsx';
            //$objWriter->save('php://output');
            $objWriter->save($name);

            $mail = Yii::$app->mailer->compose()
                ->setFrom(['idshijie@163.com' => '绣学问商城'])//发件人
                ->setTo($email)//收件人
                ->setSubject('用户收益excel')//主题
                ->setTextBody('收益内容')//文本内容
                ->attach($name)
                ->send(); //发送
            if ($mail) {
                $jsonData = ResponseHelper::buildJsonData(200, '发送成功');
            } else {
                $jsonData = ResponseHelper::buildJsonData(400, '发送失败');

            }

        }
        return $this->asJson($jsonData);

    }

    /**
     * 测试excel
     * @return Response
     */
    public function actionEmail()
    {
        $mail = Yii::$app->mailer->compose()
            ->setFrom(['idshijie@163.com' => '绣学问商城'])//发件人
            ->setTo('527777633@qq.com')//收件人
            ->setSubject('用户收益excel')//主题
            //->setTextBody('收益内容')//文本内容
            ->attach('E:\\php\\teaching\\up-rewrite.conf')
            //->attach('/data/wwwroot/default/shell/mall_amount_log/record.log')
            ->send(); //发送

        var_dump($mail);
        return $this->asJson('邮件发送');
    }

    /**
     * 测试excel
     */
    public function actionExcelTest()
    {
        $MallBill = MallBill::find()->all();

        $objPHPExcel = new PHPExcel();
        //$objPHPExcel->getActiveSheet()->getColumnDimension(\PHPExcel_cell::stringFromColumnIndex(0))->setAutoSize(true);
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '用户id')
            ->setCellValue('B1', '订单号')
            ->setCellValue('C1', '金额')
            ->setCellValue('D1', '来源')
            ->setCellValue('E1', '获得时间')
            ->setCellValue('F1', '结算时间');

        foreach ($MallBill as $key => $value) {
            $num = $key + 2;
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . $num, $value['uid'])
                ->setCellValue('B' . $num, $value['out_trade_no'])
                ->setCellValue('C' . $num, $value['amount'])
                ->setCellValue('D' . $num, $value['direct_text'])
                ->setCellValue('E' . $num, date("Y-m-d H:i:s", $value['create_time']))
                ->setCellValue('F' . $num, $value['finish_time'] ? date("Y-m-d H:i:s", $value['finish_time']) : '');
        }

        $objPHPExcel->getActiveSheet()->setTitle('用户收益表');
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Pragma: public'); // HTTP/1.0
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $name = 'excel/abc.xlsx';
        //$objWriter->save('php://output');
        $objWriter->save($name);
        exit;
    }

    /**
     * 获取一条订单详情
     * @return Response
     */
    public function actionOrder()
    {
        $request = Yii::$app->request;
        //$uid = $request->post('uid');
        $out_trade_no = $request->post('out_trade_no');
        $mid = $request->post('mid');

        $msg = '';
        $flag = false;

        if (!$mid) {
            $msg = 'mid  不能为空';
        } elseif (!$out_trade_no) {
            $msg = 'out_trade_no 不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {

            $shops = new ShopService();
            //TODO 传过来的out_trade_no 判断用户是否 No-A 开头,然后查找不同的表
            $str = substr(trim($out_trade_no),0, 4);
            $where = " mid = {$mid} AND out_trade_no = '{$out_trade_no}' ";
            if ($str == "No-A") {
                $order = $shops->orderOneAssemble($where);
            } else {
                $order = $shops->orderOne($where);
            }
            $jsonData = ResponseHelper::buildJsonData(200, '成功', $order);
        }
        return $this->asJson($jsonData);
    }

    /**
     * 查找会计账号
     * @return Response
     */
    public function actionFinance()
    {
        $request = Yii::$app->request;

        $mid = $request->post('mid');
        $roles = $request->post('roles');

        $msg = '';
        $flag = false;

        if (!$mid) {
            $msg = 'mid 商家id不能为空';
        } elseif (!$roles) {
            $msg = 'roles 不能为空';
        } elseif ($roles != 1) {
            $msg = 'roles 错误';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            $shopService = new ShopService();
            $map = "u.mall_id = {$mid} AND u.roles = {$roles}";
            $user = $shopService->financeGet($map);
            $jsonData = ResponseHelper::buildJsonData(200, '成功', $user);
        }
        return $this->asJson($jsonData);
    }

    /**
     * 设置财务账号
     * @return Response
     */
    public function actionSetFinance()
    {
        $request = Yii::$app->request;

        $mid = $request->post('mid');
        $phone = $request->post('phone');
        $wechat = $request->post('wechat');
        $roles = $request->post('roles');

        $msg = '';
        $flag = false;

        if (!$mid) {
            $msg = 'mid 商家id不能为空';
        } elseif (!$phone) {
            $msg = 'phone 手机号不能为空';
        } elseif (!$wechat) {
            $msg = '微信号不能为空';
        } elseif ($roles != 1) {
            $msg = 'roles 有误';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(200, $msg);
        } else {
            $shopService = new ShopService();

            //查看财务是否已经设置了
            $whereFilter = "mall_id = {$mid} AND roles = 1";
            $finance  = $shopService->financeOne($whereFilter);
            if ($finance) {
                $jsonData = ResponseHelper::buildJsonData(400, '财务账号已经设置了一个');
                return $this->asJson($jsonData);
            }

            //查看是否存在此用户 是否已经设置为了财务账号
            $where = " mall_id = {$mid} AND phone = '{$phone}'";
            $user = $shopService->financeOne($where);
            if (!$user) {
                $jsonData = ResponseHelper::buildJsonData(400, '查无此用户,请核实后再添加');
                return $this->asJson($jsonData);
            }
            if ($user['roles'] == 1) {
                $jsonData = ResponseHelper::buildJsonData(400, '此用户已经设置为财务账号');
                return $this->asJson($jsonData);
            } else {
                //存在并且不是财务的角色 设置进去
                $map = "roles = {$roles}";
                $andWhere = "id = {$user['id']}";
                $result = $shopService->financeUpdate($map, $andWhere);
                if ($result) {
                    //记录
                    $mapWhere = [
                        'mid' => $mid,
                        'phone' => $phone,
                        'uid' => $user['id'],
                        'wechat' => $wechat,
                        'roles' => $roles,
                        'create_time' => time(),
                        'status' => 1
                    ];
                    $shopService->financeRecord($mapWhere);
                    $jsonData = ResponseHelper::buildJsonData(200, '设置成功');
                } else {
                    $jsonData = ResponseHelper::buildJsonData(400, '设置失败');
                }

            }

        }
        return $this->asJson($jsonData);
    }

}